#include<vector>

#include <QFile>
#include <QPair>
#include <QDebug>

#include "../getpath/getpath.h"
#include "../opxml/tinyxml.h"
#include "mapsize.h"

#define MapCfgFile "/mapCfgFile.cfg"
#define RELATION "Relatation"
#define FILESIZE_STR "dFileSize"
#define MULTIMES_STR "dMultimes"

const double KB_SIZE = 1024;
//缩放倍数相关
const double MUL_TIMES_START = -1;
const double MUL_SCALE_START = 0.04;
const double MUL_NOPATH = 1.0;

using std::vector;


MapFileSize::MapFileSize()
{
    resetMulTimes();

    QString qstrFilePath = Getpath::getRootPath() + MapCfgFile;

    m_qlstCompareScale.clear();

    m_pRwXml = new RwXml(qstrFilePath.toStdString().c_str());
    if(nullptr == m_pRwXml->getDoc())
    {
        qDebug()<<"MapFileSize 加载"<<qstrFilePath<<"失败\n";
        return;
    }

    vector<TiXmlNode *> vecRelation = m_pRwXml->getNodeVec(RELATION);
    if(vecRelation.empty())
    {
        qDebug()<<"地图配置文件中不包含Road节点\n";
        return;
    }

    for(TiXmlNode *pXmlNode: vecRelation)
    {
        if(nullptr == pXmlNode || nullptr == pXmlNode->ToElement())
        {
            continue;
        }

        TiXmlElement *pEle =  pXmlNode->ToElement();

        const char *pFileSize = pXmlNode->ToElement()->Attribute("dFileSize");
        const char *pMultimes = pXmlNode->ToElement()->Attribute("dMultimes");

        double dFileSize = atof(pXmlNode->ToElement()->Attribute(FILESIZE_STR));
        double dMultimes = atof(pXmlNode->ToElement()->Attribute(MULTIMES_STR));

        m_qlstCompareScale.append(QPair<double, double>(dFileSize, dMultimes));
    }

}

MapFileSize::~MapFileSize()
{
    delete m_pRwXml;
}

void MapFileSize::inputMapFile(QString qstrMapFile)
{
    resetMulTimes();

    QFileInfo qFileInfo = QFileInfo(qstrMapFile);
    if(!qFileInfo.exists())
    {
        qDebug()<< "Map File not Exist!!!\n";
        m_dMulTimes = MUL_NOPATH;
        return;
    }    

    double dFileSize = qFileInfo.size() / KB_SIZE;
    for(auto pairMulTime: m_qlstCompareScale)
    {
        if(dFileSize < pairMulTime.first)
        {
            m_dMulTimes = pairMulTime.second;
            break;
        }
    }
}


double MapFileSize::getMapScale() const
{
    return m_dMulTimes;
}

void MapFileSize::resetMulTimes()
{
    m_dMulTimes = MUL_SCALE_START;
}
